package org.anyin.gitee.cloud.center.auth.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.anyin.gitee.cloud.center.auth.enums.AuthExCodeEnum;
import org.anyin.gitee.cloud.center.auth.extension.LoginHandler;
import org.anyin.gitee.cloud.center.auth.extension.dto.LoginUserDTO;
import org.anyin.gitee.cloud.center.auth.service.LoginService;
import org.anyin.gitee.cloud.center.auth.service.dto.LoginDTO;
import org.anyin.gitee.cloud.center.upms.api.SysUserFeignApi;
import org.anyin.gitee.cloud.center.upms.api.resp.SysUserPermissionResp;
import org.anyin.gitee.cloud.lib.core.cache.CacheTemplate;
import org.anyin.gitee.cloud.lib.core.extension.IExtensionHandlerFactory;
import org.anyin.gitee.cloud.lib.core.web.ApiResponse;
import org.anyin.gitee.cloud.lib.permission.PermissionRedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private IExtensionHandlerFactory extensionHandlerFactory;

    @Autowired
    private CacheTemplate cacheTemplate;

    @Autowired
    private SysUserFeignApi sysUserFeignApi;


    @Override
    public LoginUserDTO login(LoginDTO param) {
        LoginHandler handler = extensionHandlerFactory.getExtensionHandler(param.getType(), LoginHandler.class);
        LoginUserDTO loginUser = null;
        switch (param.getType()) {
            case MOBILE:
                loginUser = handler.login(param.getMobile(), param.getCode());
                break;
            case USERNAME:
                loginUser = handler.login(param.getUsername(), param.getPassword());
                break;
            case EMAIL:
                loginUser = handler.login(param.getEmail(), param.getPassword());
                break;
        }
        if(loginUser == null || loginUser.getSysUser() == null){
            throw AuthExCodeEnum.USER_LOGIN_ERROR.getException();
        }
        // cache permission and role to redis
        ApiResponse<SysUserPermissionResp> response = sysUserFeignApi.permissionById(loginUser.getSysUser().getId());
        if(response.getData() != null){
            String permissionKey = PermissionRedisConstant.DEFAULT_USER_PERMISSION_PREFIX + loginUser.getSysUser().getId();
            cacheTemplate.valueSet(permissionKey, response.getData().getPermissionList());

            String roleKey = PermissionRedisConstant.DEFAULT_USER_ROLE_PREFIX + loginUser.getSysUser().getId();
            cacheTemplate.valueSet(roleKey, response.getData().getRoleList());
        }
        return loginUser;
    }
}
